package com.lanyam.travel.base.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lanyam.travel.base.dao.DistrUserMapper;
import com.lanyam.travel.base.entity.DistrRecord;
import com.lanyam.travel.base.entity.DistrUser;
import com.lanyam.travel.base.entity.vo.DistrRecordVo;
import com.lanyam.travel.base.dao.DistrRecordMapper;
import com.lanyam.travel.base.entity.vo.DistrSettingVo;
import com.lanyam.travel.base.entity.vo.DistrUserVo;
import com.lanyam.travel.base.service.IDistrRecordService;
import com.lanyam.travel.base.service.IDistrSettingService;
import com.lanyam.travel.base.utils.JSONResult;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;
import javax.annotation.Resource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.util.StringUtils;


@Service
@Transactional
@Slf4j
public class DistrRecordServiceImpl implements IDistrRecordService {

    @Resource
    private DistrRecordMapper distrRecordMapper;
    @Resource
    private IDistrSettingService iDistrSettingService;
    @Resource
    private DistrUserMapper distrUserMapper;

    @Override
    public IPage<DistrRecordVo> getPageDistrRecord (Map<String, Object> queryMap, Integer page, Integer rows) {
        Page<DistrRecordVo> pageSize = new Page<DistrRecordVo>(page, rows);
        Page<DistrRecordVo> pageInfo = distrRecordMapper.getPage(pageSize, queryMap);
        return pageInfo;
    }

    @Override
    public void addDistrRecord(DistrRecord distrRecord) {
        distrRecordMapper.insert(distrRecord);
    }

    @Override
    public void updateDistrRecord(DistrRecord distrRecord) {
        distrRecordMapper.updateById(distrRecord);
    }

    @Override
    public void delById(String id) {
        distrRecordMapper.delById(id);
    }

    @Override
    public JSONResult getCommission(String distrUserId, BigDecimal orderMoney, String orderId) {
        //找到链式分销商
        DistrUserVo DistrUserline = getDistrUserLine(distrUserId,0,3);
        //找到分销规则
        IPage<DistrSettingVo> setingPage= iDistrSettingService.getPageDistrSetting(new HashMap<>(),1,1);
        DistrSettingVo setingVO = setingPage.getRecords().get(0);
        List<Map<String,String>> seting= JSON.parseObject(setingVO.getSettingInfo(), new TypeReference<List<Map<String, String>>>() {});
        Map<String,Map<String,String>> setingMap = new HashMap<>();
        seting.forEach(x -> setingMap.put(x.get("disLevel"),x));
        //生成分销记录
        List<DistrRecord> recordList = new ArrayList<>();
        recordList = getDistrRecordListByOrderId( DistrUserline, orderId, orderMoney,
                setingMap,recordList);
        //记录分销并改变余额
        recordList.forEach(x ->{
            distrRecordMapper.insert(x);
            DistrUser y = new DistrUser();
            y.setId(x.getDistUserId());
            y.setAmount(x.getNewAmount());
            distrUserMapper.updateById(y);
        });
        //返回分销记录
        Map<String,Object> re = new HashMap<>();
        re.put("isAuto",setingVO.getIsAuto());
        re.put("recordList",recordList);
        return JSONResult.ok(re);
    }

    private List<DistrRecord> getDistrRecordListByOrderId(DistrUserVo DistrUserline,String orderId,BigDecimal orderMoney,
                                                          Map<String,Map<String,String>> setingMap,List<DistrRecord> re){
        BigDecimal thisRecord = BigDecimal.ZERO;
        DistrRecord re1 =new DistrRecord();
        re1.setDistUserId(DistrUserline.getId());
        re1.setUserId(DistrUserline.getUserId());
        re1.setCreateTime(new Date());
        re1.setOldAmount(DistrUserline.getAmount());
        re1.setOrderId(orderId);
        Integer level  = DistrUserline.getDislevel();

        if(setingMap.containsKey(level.toString())){
            Map<String,String>  re1Seting= setingMap.get(level.toString());
            re1.setRatio(JSON.toJSONString(re1Seting));
            if("0".equals(re1Seting.get("disType"))){
                thisRecord =new BigDecimal(re1Seting.get("disNum")).multiply(orderMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if("1".equals(re1Seting.get("disType"))){
                thisRecord = new BigDecimal(re1Seting.get("disNum"));
            }
        }else{
            Map<String,String>  re1Seting= setingMap.get("defult");
            re1.setRatio(JSON.toJSONString(re1Seting));
            if("0".equals(re1Seting.get("disType"))){
                thisRecord =new BigDecimal(re1Seting.get("disNum")).multiply(orderMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if("1".equals(re1Seting.get("disType"))){
                thisRecord = new BigDecimal(re1Seting.get("disNum"));
            }
        }
        re1.setAmount(thisRecord);
        re1.setNewAmount(re1.getOldAmount().add(thisRecord));
        re.add(re1);
        if(DistrUserline.getFather() != null){
            //todo 所有计算按照orderMoney，可替换成thisRecord
            return getDistrRecordListByOrderId(DistrUserline.getFather(),orderId,orderMoney,setingMap,re);
        }else{
            return re;
        }
    }

    private DistrUserVo getDistrUserLine(String distrUserId,Integer now,Integer limit){
        if(now>=limit){
            return null;
        }
        DistrUserVo root = new DistrUserVo();
        Map<String, Object> queryMap =new HashMap<>();
        queryMap.put("user_id",distrUserId);
        List<DistrUser> roots = distrUserMapper.selectByMap(queryMap);
        if(CollectionUtils.isNotEmpty(roots)){
            DistrUser du = roots.get(0);
            BeanUtils.copyProperties(du, root);

            String fuID = root.getFatherUserid();
            if(!StringUtils.isEmpty(fuID) && !"#".equals(fuID)){
                queryMap.clear();
                queryMap.put("userId",fuID);
                List<DistrUser> fathers = distrUserMapper.selectByMap(queryMap);
                if(CollectionUtils.isNotEmpty(fathers)){
                    root.setFather(getDistrUserLine(fathers.get(0).getId(),now+1,limit));
                }
            }
        }
        return root;
    }

    @Override
    public List<DistrRecordVo> getDistrRecordByTeamId(String teamId){
        return distrRecordMapper.getDistrRecordByTeamId(teamId);
    }

	@Override
	public List<DistrRecordVo> getRecordsByOrderId(String orderId) {
		// TODO Auto-generated method stub
		List<DistrRecordVo> selectList = distrRecordMapper.getListByOrderId(orderId);
		return selectList;
	}

	@Override
	public void deleteByOrderId(String id) {
		// TODO Auto-generated method stub
		QueryWrapper<DistrRecord> wrapper = new QueryWrapper<DistrRecord>();
		wrapper.eq("order_id", id);
		distrRecordMapper.delete(wrapper);
	}

}